<?php

namespace backend\controllers;

use Yii;
use common\models\discount\FullCut;
use backend\models\FullCutSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\discount\FullCutSet;

/**
 * FullCutController implements the CRUD actions for FullCut model.
 */
class FullCutController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all FullCut models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new FullCutSearch();
     
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single FullCut model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new FullCut model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new \backend\models\FullCut();
        $params = [];
        if(Yii::$app->request->isPost) {
            $params = Yii::$app->request->post();
            $model->total_amount = $params['total_amount'];
            $model->discount_amount = $params['discount_amount'];
            
            //超过三条
            if(count($params['total_amount']) > 3) {
                return $this->render('create', ['model' => $model]);
            }
        }
        
        if ($model->load($params) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->full_cut_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing FullCut model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        
        $params = [];
        if(Yii::$app->request->isPost) {
            $params = Yii::$app->request->post();
            $model->total_amount = $params['total_amount'];
            $model->discount_amount = $params['discount_amount'];
            
            //超过三条
            if(count($params['total_amount']) > 3) {
                return $this->render('create', ['model' => $model]);
            }
        }
        
        if ($model->load($params) && $model->save()) {
            return $this->redirect(['index', 'id' => $model->full_cut_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing FullCut model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        FullCutSet::deleteAll(['full_cut_id'=>$id]);
        return $this->redirect(['index']);
    }

    /**
     * Finds the FullCut model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return FullCut the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = \backend\models\FullCut::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    /**
     * ajax改变活动状态c_status【上线|下线】
     */
    public function actionChangeStatus()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
        $id = Yii::$app->request->post('id');
        if(intval($id) < 1) {
            return ['flag'=>false,'msg'=>'缺少参数'];
        }
        
        $result = FullCut::findOne(['full_cut_id'=>$id]);
        
        if(empty($result)) {
            return ['flag'=>false,'msg'=>'未查询到信息'];
        }
        
        $c_status = $result->c_status == 0 ? 1 : 0;
        
        if($result->c_status == FullCut::$STATUS_INLINE && $c_status == 1 && time() > strtotime($result->end_time)) {
            return ['flag'=>false,'msg'=>'过期活动无法上线'];
        }
        
        if($result->c_status ==0) {
            $megs =  $this->tipsMesages(strtotime($result->begin_time), strtotime($result->end_time));
            if(!$megs['flag']) {
                return $megs;
            }
        }
        
        $result->c_status = $c_status;
        
        $result->save();

        return ['flag'=>true,'msg'=>'修改成功','c_status'=>$c_status];
    
    }
    
    /**
     * 检查时间
     * @return boolean[]|string[]
     */
    public function actionCheckDate(){
        
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $begin_time = Yii::$app->request->post('begin_time','');//开始时间
        $end_time = Yii::$app->request->post('end_time','');//结束时间
        $id = Yii::$app->request->post('id',0);//id
        if(empty($begin_time) || empty($end_time)) {
            return ['flag'=>false,'msg'=>'请设置活动时间'];
        }
        
        $begin_time = strtotime($begin_time);
        $end_time = strtotime($end_time);
        
        if( $begin_time > $end_time) {
            
            return ['flag'=>false,'msg'=>'开始日期不能晚于结束日期！'];
        }
        if($end_time < time()) {
            return ['flag'=>false,'msg'=>'结束时间时间不能小于当前时间'];
        }
        
        $sigle_info = FullCut::findOne(['full_cut_id'=>$id]);
        
        if(!empty($sigle_info) && (strtotime($sigle_info->begin_time)-600 ) < time() ){
            return ['flag'=>false,'msg'=>'距离活动上线十分钟之前不可更改|下线的活动不可再次编辑'];
        }
        
        $res =  $this->tipsMesages($begin_time, $end_time);
        
        return $res;
        
    }
    
    private function tipsMesages($begin_time,$end_time) {
        
        $info = FullCut::find()
        ->where(['c_status'=>FullCut::$STATUS_ONLINE,'c_obj'=>FullCut::$OBJ_ALL,'c_type'=>FullCut::$TYPE_BY_AMOUNT])
        ->all();
        if(!$info) {
            return ['flag'=>true,'msg'=>'success'];
        }
        foreach ($info as $item) {
            $tmp_begin_time = strtotime($item->begin_time);
            $tmp_end_time = strtotime($item->end_time);
            if($begin_time >= $tmp_begin_time && $begin_time <= $tmp_end_time){
                return ['flag'=>false,'msg'=>'当前时间范围内已有全场满减重复活动！'];
            }
            if($end_time >= $tmp_begin_time && $end_time <= $tmp_end_time){
                return ['flag'=>false,'msg'=>'当前时间范围内已有全场满减重复活动！ '];
            }
            if($tmp_begin_time >= $begin_time && $tmp_begin_time <= $end_time ){
                return ['flag'=>false,'msg'=>'当前时间范围内已有全场满减重复活动！ '];
            }
            if($tmp_end_time >= $begin_time && $tmp_end_time <= $end_time ){
                return ['flag'=>false,'msg'=>'当前时间范围内已有全场满减重复活动！ '];
            }
        }
        
        return ['flag'=>true,'msg'=>'success'];
        
    }
}
